<template>
  <div>
    <Row>
      <i-col span="6">
        <Button type="primary" size="large" @click="checkboxSelect">
          {{checkboxSelectStatue?'取消选择':'全选'}}
        </Button>
        <Button type="primary" size="large" @click="confirmDispatch">
          派单
        </Button>
        <Button type="primary" size="large" @click="confirmDispatchNoDriver">
          未指定派单
        </Button>
      </i-col>
      <i-col span="18">
        <Form ref="subOrderTabParam" :model="subOrderTabParam" label-position="right" inline>
          <FormItem>
            <Input type="text" v-model="subOrderTabParam.waybillNo" placeholder="货票号"></Input>
          </FormItem>
          <FormItem>
            <Input type="text" v-model="subOrderTabParam.containerNo" placeholder="集装箱号"></Input>
          </FormItem>
          <FormItem>
            <Input type="text" v-model="subOrderTabParam.outAddress" placeholder="送货地址"></Input>
          </FormItem>
          <FormItem>
            <Input type="text" v-model="subOrderTabParam.shipper" placeholder="收货人"></Input>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="staticTableRefFilter" icon="ios-search">
              查询
            </Button>
          </FormItem>
        </Form>
      </i-col>
    </Row>
    <staticTable :filterMethod="tableFilterMethod" ref="staticTableRef">
      <Table ref="subOrderTab" :columns="subOrderColumn" border :data="dispatchNotDataClone" style="margin-top: 15px;"
        height="600">
      </Table>
    </staticTable>
    <xlinkModal v-model="operaModal.confirmDispatchShow" title="派单" className="vertical-center-modal" width="600px;">
      <checkAddressModal v-if="operaModal.confirmDispatchShow" :dispatchDriverInfo="dispatchDriverInfo"
        :addressList="resAddressList" @dispatch="fleetDispatchDriver"></checkAddressModal>
    </xlinkModal>

    <xlinkModal v-model="operaModal.checkDriverShow" title="派单" className="vertical-center-modal" width="800px;">
      <checkDriverModal v-if="operaModal.checkDriverShow" :dispatchDriverInfo="dispatchDriverInfo"
        :addressList="resAddressList" :driverList="driverList"
        @dispatch="fleetDispatchNotDriver"></checkDriverModal>
    </xlinkModal>
  </div>
</template>

<script>
  import {getTruckTypeList} from '@api/backEnd/fleetControl'
  import {assignmentToDriver, assignmentToDriverNoAppoint} from '@api/backEnd/fleetOrder'
  import {unbindSubOrderNoWithUser} from '@api/backEnd/mainOrder'
  import {getTrainTypeCN} from './trainTypeEnum'
  import checkAddressModal from './checkAddressModal'
  import checkDriverModal from './checkDriverModal'
  import xlinkModal from '@components/modal/xlinkModal'
  import pinyin from '@components/common/pinyin'
  import _ from 'lodash'
  import staticTable from '@/components/staticTable'

  export default {
    name: 'dispatch-not',
    data () {
      let subOrderColumn = [
        {
          type: 'index',
          width: 60
        },
        {
          width: 60,
          align: 'center',
          render: (h, params) => {
            return (<checkbox v-model={params.row.check}></checkbox>)
          }
        },
        {
          title: '火车车种类型',
          ellipsis: 'false',
          width: 150,
          render: (h, params) => {
            let trainType = params.row.trainType
            let trainTypeCN = getTrainTypeCN(trainType)
            return (<span>{trainTypeCN}</span>)
          }
        },
        {
          title: '货票号',
          ellipsis: 'false',
          width: 150,
          key: 'waybillNo'
        },
        {
          title: '箱号',
          ellipsis: 'false',
          width: 150,
          key: 'containerNo'
        },
        {
          title: '掏箱',
          ellipsis: 'false',
          width: 100,
          render: (h, params) => {
            // console.log(params)
            let driverName = params.row.driverName
            let vif = params.row.check
            if (vif && !driverName) {
              // todo john 接口层需要匹配
              return (<checkbox on-on-change={(val) => this.selectTakeOutChange(val, params.row)}></checkbox>)
            } else {
              // params.row.driverId = ''
              return (<span></span>)
            }
          }
        },
        {
          title: '司机',
          ellipsis: 'false',
          width: 400,
          render: (h, params) => {
            let driverName = params.row.driverName
            let vif = params.row.check
            if (vif && !driverName) {
              let driverList = this.driverList
              let truckTypeList = this.truckTypeList
              console.log('truckTypeList', truckTypeList)
              return (<auto v-model={params.row.driverId} field="id" label="login_name"
                on-on-change={(val) => this.selectDriverChange(val, params.row)}
                search-keys="login_namePy,login_name" dataList={driverList} dropAll={true}
                groupData={truckTypeList} groupField="id" groupLabel="name" groupFilterKeys="type"></auto>)
            } else {
              params.row.driverId = ''
              return (<span></span>)
            }
          }
        },
        {
          title: '发货人',
          ellipsis: 'false',
          key: 'receiver',
          width: 250
        },
        {
          title: '收货人',
          ellipsis: 'false',
          key: 'shipper',
          width: 250
        },
        {
          title: '送货地址',
          ellipsis: 'false',
          width: 200,
          key: 'outAddress',
          render: (h, params) => {
            return (<span>{params.row.outAddress}</span>)
          }
        },
        {
          title: '联系人',
          ellipsis: 'false',
          width: 100,
          key: 'outContacts'
        },
        {
          title: '联系人电话',
          ellipsis: 'false',
          width: 150,
          key: 'outMobile'
        },
        {
          title: '品名',
          ellipsis: 'false',
          key: 'pm',
          width: 150
        },
        {
          title: '接取费(元)',
          ellipsis: 'false',
          key: 'receiveFee',
          width: 120
        },
        {
          title: '送达费(元)',
          ellipsis: 'false',
          key: 'deliverFee',
          width: 120
        },
        {
          title: '备注',
          ellipsis: 'false',
          key: 'memo',
          width: 200
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: 250,
          render: (h, params) => {
            let voucherImg = params.row.voucherImg
            let viewImg = (<i-button size="small" style="margin-right: 5px;">图片查看</i-button>)
            if (voucherImg) {
              viewImg = (<i-button type="primary" size="small" style="margin-right: 5px;"
                onClick={() => this.viewDetailImgAction(params.row)}>图片查看</i-button>)
            }
            let btnArray = []
            powerUtil.contains('orderListUnfinishedFleet') && btnArray.push(viewImg)
            return (btnArray)
          }
        }
      ]
      let resAddressList = []
      let resAddress = ''
      let dispatchNotDataClone = []
      let checkboxSelectStatue = false
      let dispatchDriverInfo = {}
      let operaModal = {confirmDispatchShow: false, checkDriverShow: false}
      let truckTypeList = []
      let subOrderTabParam = {
        waybillNo: '',
        containerNo: '',
        outAddress: '',
        shipper: ''
      }
      let datas = {
        subOrderColumn,
        resAddressList,
        resAddress,
        dispatchNotDataClone,
        checkboxSelectStatue,
        operaModal,
        truckTypeList,
        dispatchDriverInfo,
        subOrderTabParam
      }
      return datas
    },
    props: {
      driverList: {
        type: Array,
        default () {
          return []
        }
      },
      addressList: {
        type: Array,
        default () {
          return []
        }
      },
      dispatchNotData: {
        type: Array,
        default () {
          return []
        }
      },
      currentMainOrder: {
        type: Object,
        default () {
          return {}
        }
      }
    },
    computed: {},
    methods: {
      selectRow (selection, row) {
        row.check = true
      },
      confirmDispatchNoDriver () {
        let checkData = []
        this.$refs['subOrderTab'].rebuildData.forEach((item) => {
          if (item.check) {
            checkData.push(item)
          }
        })
        if (!(checkData.length > 0)) {
          this.$Notice.warning({
            title: '警告',
            desc: '请选择运单'
          })
          return
        }

        function valit (fild) {
          let currentVal = checkData[0][fild]
          for (let i = 1, counti = checkData.length; i < counti; i++) {
            if (currentVal !== checkData[i][fild]) {
              return false
            } else {
              currentVal = checkData[i][fild]
            }
          }
          return 1
        }

        console.log('chechData')
        console.log(checkData)
        if (!(checkData.length === 1 || (valit('outAddress') && valit('outContacts') && valit('outMobile') && valit('userAddressId')))) {
          this.$Notice.warning({
            title: '警告',
            desc: '选择的地址不一致'
          })
        } else {
          console.log('这是选择的一条数据将要用于派单', checkData[0])
          this.dispatchDriverInfo = {
            outAddress: checkData[0].outAddress,
            outContacts: checkData[0].outContacts,
            outMobile: checkData[0].outMobile,
            outWeight: checkData[0].weight,
            memo: checkData[0].memo,
            userAddressId: checkData[0].userAddressId
          }
          this.operaModal.checkDriverShow = true
        }
      },
      checkboxSelect () {
        if (!this.checkboxSelectStatue) {
          this.$refs['subOrderTab'].rebuildData.forEach((item) => {
            item.check = true
          })
        } else {
          this.$refs['subOrderTab'].rebuildData.forEach((item) => {
            item.check = false
          })
        }
        this.checkboxSelectStatue = !this.checkboxSelectStatue
      },
      selectDriverChange (val, row) {
        row.driverId = val
      },
      selectTakeOutChange (val, row) {
        if (val) {
          row.takeOutContainerState = 1
        }
        // console.log(val, row)
      },
      fleetDispatchDriver (otherForm) {
        console.log('therForm', otherForm)
        let param = []
        this.$refs['subOrderTab'].rebuildData.forEach((item) => {
          if (item.check && item.driverId) {
            param.push({
              id: item.id,
              fleetOrderId: item.fleetOrderId,
              subOrderId: item.subOrderId,
              driverId: item.driverId,
              outAddress: otherForm.outAddress,
              outMobile: otherForm.outMobile,
              outContacts: otherForm.outContacts,
              userAddressId: otherForm.userAddressId,
              takeOutContainerState: item.takeOutContainerState
            })
          }
        })
        if (param && param.length > 0) {
          let result = param.some((item) => {
            if (!item.driverId || !item.outAddress) {
              return true
            }
          })
          if (result) {
            this.$Message.error('司机和地址必选')
            return
          }
          assignmentToDriver(param).then(res => {
            if (+res.data.isSuccess === 1) {
              this.$Message.success('派单成功')
              this.operaModal.confirmDispatchShow = false
              this.$emit('refreshSource')
            } else {
              this.$Message.error(res.data.res)
            }
          })
        } else {
          this.$Message.error('请选择司机后派单')
        }
      },
      fleetDispatchNotDriver (otherForm) {
        console.log(otherForm)
        // return
        let param = []
        this.$refs['subOrderTab'].rebuildData.forEach((item) => {
          if (item.check && otherForm && otherForm.driverIds && otherForm.driverIds.length > 0) {
            param.push({
              id: item.id,
              fleetOrderId: item.fleetOrderId,
              subOrderId: item.subOrderId,
              driverId: JSON.stringify(otherForm.driverIds),
              outAddress: otherForm.outAddress,
              outMobile: otherForm.outMobile,
              outContacts: otherForm.outContacts,
              userAddressId: otherForm.userAddressId,
              takeOutContainerState: otherForm.checkTackOut ? 1 : 0
            })
          }
        })
        if (param && param.length > 0) {
          let result = param.some((item) => {
            if (!item.driverId || !item.outAddress) {
              return true
            }
          })
          if (result) {
            this.$Message.error('司机和地址必选')
            return
          }
          assignmentToDriverNoAppoint(param).then(res => {
            if (+res.data.isSuccess === 1) {
              this.$Message.success('派单成功')
              this.operaModal.checkDriverShow = false
              this.$emit('refreshSource')
            } else {
              this.$Message.error(res.data.res)
            }
          })
        } else {
          this.$Message.error('请选择一条数据后派单')
        }
      },
      checkRemove (val, row) {
        let param = []
        this.$refs['subOrderTab'].rebuildData.forEach((item) => {
          if (item.check) {
            param.push({mainOrderNo: item.mainOrderNo, subOrderNo: item.orderNo})
          }
        })
        if (param && param.length === 0) {
          this.$Notice.warning({
            title: '错误',
            desc: '请选择子运单'
          })
          return
        }
        unbindSubOrderNoWithUser(param).then((res) => {
          if (+res.data.isSuccess === 1) {
            this.$Notice.success({
              title: '成功',
              desc: '解绑成功'
            })
            this.$emit('refreshSource')
          }
        })
      },
      confirmDispatch () {
        let checkData = []
        this.$refs['subOrderTab'].rebuildData.forEach((item) => {
          if (item.check) {
            checkData.push(item)
          }
        })
        if (!(checkData.length > 0)) {
          this.$Notice.warning({
            title: '警告',
            desc: '请选择运单'
          })
          return
        }

        function valit (fild) {
          let currentVal = checkData[0][fild]
          for (let i = 1, counti = checkData.length; i < counti; i++) {
            // checkData[i][fild]
            if (currentVal !== checkData[i][fild]) {
              return false
            } else {
              currentVal = checkData[i][fild]
            }
          }
          return 1
        }

        console.log('checkData', checkData)
        if (!(checkData.length === 1 || (valit('outAddress') && valit('outContacts') && valit('outMobile')))) {
          this.$Notice.warning({
            title: '警告',
            desc: '选择的地址不一致'
          })
        } else {
          this.dispatchDriverInfo = {
            outAddress: checkData[0].outAddress,
            outContacts: checkData[0].outContacts,
            outMobile: checkData[0].outMobile,
            outWeight: checkData[0].weight,
            memo: checkData[0].memo,
            userAddressId: checkData[0].userAddressId
          }
          this.operaModal.confirmDispatchShow = true
        }
      },
      viewDetailImgAction (row) {
        this.$emit('viewDetailImg', row)
      },
      onShow () {
        console.log('this.dispatchNotData', this.dispatchNotData)
        this.dispatchNotDataClone = _.cloneDeep(this.dispatchNotData)
        this.dispatchNotDataClone.forEach((item) => {
          this.$set(item, 'check', false)
        })
        this.resAddressList = []
        this.addressList.forEach((item) => {
          let py = pinyin.codefans_net_CC2PY(item)
          this.resAddressList.push({
            key: item,
            keyPy: py
          })
        })
      },
      getTruckType () {
        getTruckTypeList().then(res => {
          this.truckTypeList = res.data.data
        })
      },
      tableFilterMethod (row, index) {
        if (this.subOrderTabParam.waybillNo) {
          return _.includes(row.waybillNo, this.subOrderTabParam.waybillNo)
        }
        if (this.subOrderTabParam.containerNo) {
          return _.includes(row.containerNo, this.subOrderTabParam.containerNo)
        }
        if (this.subOrderTabParam.shipper) {
          return _.includes(row.shipper, this.subOrderTabParam.shipper)
        }
        if (this.subOrderTabParam.outAddress) {
          return _.includes(row.outAddress, this.subOrderTabParam.outAddress)
        }
        return true
      },
      staticTableRefFilter () {
        this.$refs['staticTableRef'].customFilter()
        console.log('getCheckedData()', this.$refs['staticTableRef'].getCheckedData())
      }
    },
    watch: {
      'dispatchNotData.length' (val, oldVal) {
        this.onShow()
      }
    },
    mounted () {
      this.onShow()
      this.driverList.forEach((item) => {
        let py = pinyin.codefans_net_CC2PY(item.login_name)
        item.login_namePy = py
      })
      this.getTruckType()
    },
    components: {checkAddressModal, xlinkModal, checkDriverModal, staticTable}
  }
</script>

<style scoped>

</style>
